package com.ken.checkviolationapp.utils

import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import com.ken.checkviolationapp.MyApplication
import java.lang.IllegalArgumentException

/**
 * @author by ken
 * Blog:
 * Date:2020/4/28
 * Description:
 */
object SpUtil {
    private val name = "App_SharedPreferences_Data"
    val carNo = Config.App_Name + "carNo"
    val carType = Config.App_Name + "carType"
    val engineno = Config.App_Name + "engineno"
    val frameno = Config.App_Name + "frameno"

    private val sp: SharedPreferences by lazy {
        MyApplication.instant.getContext().getSharedPreferences(name, Context.MODE_PRIVATE)
    }

    init {

    }

    fun getValue(key: String, default: Any): Any = with(sp) {
        return@with when (default) {
            is Int -> getInt(key, default)
            is String -> this!!.getString(key, default)!!
            is Long -> getLong(key, default)
            is Float -> getFloat(key, default)
            is Boolean -> getBoolean(key, default)

            else -> throw IllegalArgumentException("SharedPreferences 类型错误")
        }
    }


    fun getString(key: String, default: String = ""): String {
        return getValue(key, default) as String
    }

    fun getInts(key: String, default: Int = 0): Int {
        return getValue(key, default) as Int
    }

    fun getLong(key: String, default: Long = 0): Long {
        return getValue(key, default) as Long
    }

    fun getBoolean(key: String, default: Boolean = false): Boolean {
        return getValue(key, default) as Boolean
    }

    fun getFloat(key: String, default: Float = 0f): Float {
        return getValue(key, default) as Float
    }

    /**
     * 存放SharedPreferences
     * @param key 键
     * @param value 值
     */
    fun saveValue(key: String, value: Any) = with(sp.edit()) {
        when (value) {
            is Long -> putLong(key, value)
            is Int -> putInt(key, value)
            is String -> putString(key, value)
            is Float -> putFloat(key, value)
            is Boolean -> putBoolean(key, value)
            else -> throw IllegalArgumentException("SharedPreferences 类型错误")
        }.apply()
    }

    /**
     * 清除
     */
    fun clear() {
        sp.edit().clear().apply()
    }

    /**
     * 删除某Key的值
     */
    fun remove(key: String) {
        sp.edit().remove(key).apply()
    }
}